package handlers

import (
	"backEnd/database"
	"backEnd/models"
	"backEnd/utils"
	"database/sql"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// GetUserWallList 获取我的评分/下载列表
func GetUserWallList(c *gin.Context) {
	startTime := time.Now()

	accessKey := c.GetString("access_key")
	listType := c.Query("type") // score 或 download
	pageNum, _ := strconv.Atoi(c.DefaultQuery("pageNum", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "9"))
	offset := (pageNum - 1) * pageSize

	if listType != "score" && listType != "download" {
		c.JSON(http.StatusOK, models.Response{
			ErrCode:  400,
			ErrMsg:   "type参数必须是score或download",
			Data:     nil,
			TimeCost: time.Since(startTime).Milliseconds(),
		})
		return
	}

	var query string
	if listType == "score" {
		query = `
			SELECT w.id, w.classid, wc.name as classname, w.description, w.small_picurl, 
			       w.score, w.nickname,
			       GROUP_CONCAT(wt.tag_name ORDER BY wt.tag_name SEPARATOR ',') as tags,
			       us.user_score, us.create_time
			FROM user_score us
			JOIN wallpaper w ON us.wallpaper_id = w.id
			LEFT JOIN wallpaper_classify wc ON w.classid = wc.id
			LEFT JOIN wallpaper_tag wt ON w.id = wt.wallpaper_id
			WHERE us.access_key = ?
			GROUP BY w.id, w.classid, wc.name, w.description, w.small_picurl, w.score, w.nickname, us.user_score, us.create_time
			ORDER BY us.create_time DESC
			LIMIT ? OFFSET ?
		`
	} else {
		query = `
			SELECT w.id, w.classid, wc.name as classname, w.description, w.small_picurl, 
			       w.score, w.nickname,
			       GROUP_CONCAT(wt.tag_name ORDER BY wt.tag_name SEPARATOR ',') as tags,
			       ud.create_time
			FROM user_download ud
			JOIN wallpaper w ON ud.wallpaper_id = w.id
			LEFT JOIN wallpaper_classify wc ON w.classid = wc.id
			LEFT JOIN wallpaper_tag wt ON w.id = wt.wallpaper_id
			WHERE ud.access_key = ?
			GROUP BY w.id, w.classid, wc.name, w.description, w.small_picurl, w.score, w.nickname, ud.create_time
			ORDER BY ud.create_time DESC
			LIMIT ? OFFSET ?
		`
	}

	rows, err := database.DB.Query(query, accessKey, pageSize, offset)
	if err != nil {
		c.JSON(http.StatusOK, models.Response{
			ErrCode:  400,
			ErrMsg:   "查询失败",
			Data:     nil,
			TimeCost: time.Since(startTime).Milliseconds(),
		})
		return
	}
	defer rows.Close()

	var wallpapers []models.Wallpaper
	for rows.Next() {
		var wallpaper models.Wallpaper
		var tabsStr sql.NullString
		var score sql.NullFloat64
		var createTime int64

		if listType == "score" {
			var userScore sql.NullString
			err := rows.Scan(&wallpaper.ID, &wallpaper.ClassID, &wallpaper.ClassName, &wallpaper.Description, &wallpaper.SmallPicURL, &score, &wallpaper.Nickname, &tabsStr, &userScore, &createTime)
			if err != nil {
				continue
			}
			if userScore.Valid {
				wallpaper.UserScore = userScore.String
			}
		} else {
			err := rows.Scan(&wallpaper.ID, &wallpaper.ClassID, &wallpaper.ClassName, &wallpaper.Description, &wallpaper.SmallPicURL, &score, &wallpaper.Nickname, &tabsStr, &createTime)
			if err != nil {
				continue
			}
		}

		if score.Valid {
			wallpaper.Score = utils.FormatFloat(score.Float64)
		} else {
			wallpaper.Score = "0"
		}

		if tabsStr.Valid {
			wallpaper.Tabs = utils.ParseTabsString(tabsStr.String)
		} else {
			wallpaper.Tabs = []string{}
		}

		wallpaper.CreateTime = createTime
		wallpapers = append(wallpapers, wallpaper)
	}

	c.JSON(http.StatusOK, models.Response{
		ErrCode:  0,
		ErrMsg:   "查询成功",
		Data:     wallpapers,
		TimeCost: time.Since(startTime).Milliseconds(),
	})
}

// GetUserInfo 获取用户个人信息
func GetUserInfo(c *gin.Context) {
	startTime := time.Now()

	accessKey := c.GetString("access_key")
	now := utils.GetCurrentTimestamp()
	cacheTime := now - 5*60*1000 // 5分钟前的缓存时间

	var userInfo models.UserInfo
	var cacheTimeDB int64

	// 查询用户信息
	query := `
		SELECT ip, country, province, city, download_size, score_size, cache_time
		FROM user_info
		WHERE access_key = ?
	`

	err := database.DB.QueryRow(query, accessKey).Scan(
		&userInfo.IP, &userInfo.Address.Country, &userInfo.Address.Province, &userInfo.Address.City,
		&userInfo.DownloadSize, &userInfo.ScoreSize, &cacheTimeDB,
	)

	// 如果缓存过期，更新统计数据
	if err == sql.ErrNoRows || cacheTimeDB < cacheTime {
		// 统计下载次数
		var downloadSize int
		database.DB.QueryRow("SELECT COUNT(*) FROM user_download WHERE access_key = ?", accessKey).Scan(&downloadSize)

		// 统计评分次数
		var scoreSize int
		database.DB.QueryRow("SELECT COUNT(*) FROM user_score WHERE access_key = ?", accessKey).Scan(&scoreSize)

		// 更新或插入用户信息
		if err == sql.ErrNoRows {
			// 插入新记录
			insertQuery := `
				INSERT INTO user_info (access_key, ip, country, province, city, download_size, score_size, cache_time, create_time, update_time)
				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
			`
			// 这里可以从请求中获取IP和地址信息
			ip := c.ClientIP()
			database.DB.Exec(insertQuery, accessKey, ip, "", "", "", downloadSize, scoreSize, now, now, now)
			userInfo.IP = ip
			userInfo.DownloadSize = downloadSize
			userInfo.ScoreSize = scoreSize
		} else {
			// 更新记录
			updateQuery := `
				UPDATE user_info 
				SET download_size = ?, score_size = ?, cache_time = ?, update_time = ?
				WHERE access_key = ?
			`
			database.DB.Exec(updateQuery, downloadSize, scoreSize, now, now, accessKey)
			userInfo.DownloadSize = downloadSize
			userInfo.ScoreSize = scoreSize
			if userInfo.IP == "" {
				userInfo.IP = c.ClientIP()
			}
		}
	}

	c.JSON(http.StatusOK, models.Response{
		ErrCode:  0,
		ErrMsg:   "查询成功",
		Data:     userInfo,
		TimeCost: time.Since(startTime).Milliseconds(),
	})
}
